package com.enki.cigarettes.utils.qiniu;

import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.*;

/**
 * @author WCS.Wang
 * @version V1.0
 * @Package com.enki.cigarettes.utils.qiniu
 * @Name e-cigarettes-shop-api-module
 * @Description: TODO 七牛上传工具类
 * @date 2019-08-16
 */
@Component
public class QiNiuUtils {

    @Autowired
    QiNiuConfig staticQiNiuConfig;

    private static QiNiuConfig qiNiuConfig;

    @PostConstruct
    public void init() {
        qiNiuConfig = staticQiNiuConfig;
    }


    /**
     * 七牛图片上传
     *
     * @param filePath 待上传文件的硬盘路径
     * @param fileName 待上传文件的文件名
     * @param key      空间内文件的key
     * @return
     */
    public static void uploadFileByte(String filePath, String fileName, String key) {
        try {
            Auth auth = Auth.create(qiNiuConfig.getAccesskey(), qiNiuConfig.getSecretkey());
            String token = auth.uploadToken(qiNiuConfig.getBucketname());
            InputStream inputStream = new FileInputStream(new File(filePath));
            byte[] bytes = IOUtils.toByteArray(inputStream);
            UploadManager uploadManager = new UploadManager(new Configuration(Zone.huanan()));
            Response response = uploadManager.put(bytes, (key == null || "".equals(key)) ? fileName : key, token);
            inputStream.close();
            //return response.bodyString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 七牛图片上传
     *
     * @param filePath 待上传文件的硬盘路径
     * @param key      空间内文件的key
     * @return
     */
    public static void uploadFile(String filePath, String key) {
        try {
            Auth auth = Auth.create(qiNiuConfig.getAccesskey(), qiNiuConfig.getSecretkey());
            String token = auth.uploadToken(qiNiuConfig.getBucketname());
            UploadManager uploadManager = new UploadManager(new Configuration(Zone.huanan()));
            Response response = uploadManager.put(filePath, key, token);
            //return response.bodyString();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
